// index.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dktrue: true, //是否需要显示打卡
    nowt: Math.floor(new Date().getTime() / 1000), //当前时间戳
    project_name: '打卡',
    page:1,
    limit:1,
    qq:true,
    articleGetlist:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _this = this;
    _this.getuserlist();
    _this.getArticlelist();
  },
  // 打卡内容
  getuserlist() {
    var _this = this;
    wx.showLoading()
    var params = {
      url: app.api_list.user_clockin_log,
      method: "GET",
      data: {
        page: _this.data.page,
        size: 1
      },
      callBack: function (res) {
        if (res.data.length) {
          const getuserlist = _this.addNewPropertyToArray(res.data, 't', res.data);
          var k = _this.findItemWithTrueValue(getuserlist, 'isInRange');
          if (typeof k == 'number') {
            var project_name = getuserlist[k].project_name;
            if(getuserlist[k].is_clocked == 1){
              project_name = "已打卡"
            }else{
              project_name = "打卡"
            }
          }else{
            project_name = '暂无打卡项'
          }
          _this.setData({
            getuserlist: getuserlist,
            project_name:project_name,
          });
        } else {
          _this.setData({
            dktrue: false,
          })
        }
      }
    }
    app.http.request(params)
  },
  // 打卡
  fydk() {
    var _this = this;
    var getuserlist = _this.data.getuserlist;
    var k = _this.findItemWithTrueValue(getuserlist, 'isInRange');
    if (typeof k == 'number') {
      if (getuserlist[k].is_clocked == 0) {
        var params = {
          url: app.api_list.do_clockin,
          method: 'post',
          data: {
            "id": getuserlist[k].id,
          },
          callBack: function (response) {
            console.log('do clockcin',response);
            if (response.error_code == 0) {
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: response.data.msg,
                success: function (res) {
                  wx.navigateBack({
                    delta: 1
                  });
                }
              })
              _this.setData({
                project_name: '已打卡'
              })
            }
          },
          fail: function (error) {
            console.error('请求服务器失败：', error);
          }
        };
      } else {
        wx.showModal({
          title: '已打卡',
          showCancel: false,
          success: function (res) {
            wx.navigateBack({
              delta: 1
            });
          }
        })
      }
      
    app.http.request(params)
    } else {
      wx.showModal({
        title: '未在打卡时间',
        showCancel: false,
        success: function (res) {
          wx.navigateBack({
            delta: 1
          });
        }
      })
    }
  },

  findItemWithTrueValue(items, key) {
    console.log(items, key);
    for (let i = 0; i < items.length; i++) {
      if (items[i][key] === true && items[i]['is_clocked'] == 0) {
        // return items[i];
        return i;
      }
    }
    // return null;
    return 'err';
  },
  // 文章列表
  getArticlelist() {
    var _this = this;
    var params = {
      url: app.api_list.get_article_list,
      method: 'get',
      data:{
        page:_this.data.page,
        limit:_this.data.limit,
      },
      callBack:function(res){
        console.log('article_list_res',res)
        if (res.data.data.length) {
          var tata = res.data.data;
          var p =  _this.data.page;
          var qq = true;
          if(tata.length>=_this.data.limit){
            p++;
          }else{
            qq = false;
          }
          var articleGetlist = _this.data.articleGetlist.concat(res.data.data);
          console.log('articleGetlist',articleGetlist);
          _this.setData({
            articleGetlist: articleGetlist,
            page:p,
            qq:qq,
          })
        }
      }
    }
    app.http.request(params);
  },
  // 定义一个方法，用于为数组中的每个对象添加新的属性
  addNewPropertyToArray(array, propertyName, propertyValue, stringToTimestamp) {
    var _this = this;
    var sts = "sts";
    var isInRange = "isInRange"; //是否可打卡
    var startTimestamp; //时间范围时间戳
    var endTimestamp; //时间范围时间戳
    return array.map(item => {
      propertyValue = item.expect_clock_intime.substring(11, 16);
      stringToTimestamp = _this.stringToTimestamp(item.expect_clock_intime);
      endTimestamp = _this.stringToTimestamp(item.expect_clock_intime) + (item.permissible_error * 60);
      startTimestamp = _this.stringToTimestamp(item.expect_clock_intime) - (item.permissible_error * 60);
      return {
        ...item,
        [propertyName]: propertyValue,
        [sts]: stringToTimestamp,
        [isInRange]: _this.isCurrentTimestampInRange(startTimestamp, endTimestamp,item.is_clocked),
      };
    });
  },
  // 时间戳范围
  isCurrentTimestampInRange: function (startTimestamp, endTimestamp,is_clocked) {
    const currentTimestamp = Math.floor(new Date().getTime() / 1000);
    console.log(startTimestamp, endTimestamp, currentTimestamp);
    var res = currentTimestamp >= startTimestamp && currentTimestamp <= endTimestamp;
    if(res){
      return true;
    }else{
      return false;
    }
  },
  // 时间戳
  stringToTimestamp: function (str) {
    const date = new Date(str);
    return Math.floor(date.getTime() / 1000);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    var _this = this
    if(_this.data.qq){
      _this.setData({
        qq:false,
      })
      _this.getArticlelist();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})